import {
  request
} from "../../request/index.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {},
    isShouCang: false
  },
  goodsInfo: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.goods_id);
    this.getGoodsDetail(options.goods_id);
  },
  async getGoodsDetail(goods_id) {
    let data = await request({
      url: "https://api-hmugo-web.itheima.net/api/public/v1/goods/detail",
      data: {
        goods_id
      }
    })
    console.log(data.data.message);
    this.setData({
      goodsObj: {
        pics: data.data.message.pics,
        goods_price: data.data.message.goods_price,
        goods_name: data.data.message.goods_name,
        goods_introduce: data.data.message.goods_introduce.replace(/\.webp/g, '.jpg'),
      }
    })
    this.goodsInfo = data.data.message;
  },
  handlePreviewImage(e) { //点击放大预览图片
    let urlImg = [];
    this.data.goodsObj.pics.forEach((val, index) => {
      urlImg.push(val.pics_mid)
    });
    console.log(urlImg);
    console.log(e.currentTarget.dataset.index);
    wx.previewImage({
      urls: urlImg,
      current: urlImg[e.currentTarget.dataset.index]
    })
  },
  tapCollected() { //点击收藏
    let isShouCang = !this.data.isShouCang;
    console.log(isShouCang);
    this.setData({
      isShouCang
    })
  },
  handleCartAdd() { //点击添加购物车
    let cart = wx.getStorageSync("cart") || [];//判断本地缓存中有没有数据，没有默认为数组，有就取出来
    let index = cart.findIndex(val => val.goods_id == this.goodsInfo.goods_id)//findIndex函数必须要有return返回
    console.log(index);
    if (index === -1) {//本地缓存中没有对应的商品索引，表示没有点击添加购物车，那么让商品数量为1，将该商品加入数据数组中
      this.goodsInfo.num = 1;
      this.goodsInfo.checked = true;
      cart.push(this.goodsInfo);
    } else {//表示本地缓存已经有该商品的信息，点击添加购物车的话，商品数量+1
      cart[index].num++;
    }
    wx.setStorageSync("cart", cart);//无论是添加商品还是添加商品数量都要再进行存储到本地缓存中
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true
    });
  }
})